<template>
  <a-spin :spinning="confirmLoading">

    <a-form :form="form">
      <a-row>
        <a-col :xs="24" :sm="12">
          <a-form-item label="合同信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-search-select-tag v-decorator="['leaseContractId', validatorRules.leaseContractId]" :disabled="isDisabled"
                                 :async="true"  dict="zcgl_lease_contract_info,contract_num,id" @change="changeLease"/> <!--,status>10-->
          </a-form-item>
        </a-col>

        <a-col v-if="!isReadOnly" :xs="24" :sm="12">
          <a-form-item label="资产信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-search-select-tag v-decorator="['assetId', validatorRules.assetId]" :disabled="isDisabled"
                                 @change="selectSub"
                                 :async="true"      dict="zcgl_asset_info,asset_name,id"/> <!--,status>1-->
          </a-form-item>
        </a-col>

        <a-col v-if="!isReadOnly" :xs="24" :sm="12">
          <a-form-item label="资产明细" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-search-select-tag
              :trigger-change="true"
              v-decorator="['assetSubIds', validatorRules.assetSubIds]"
              :dictOptions="searchOptions"
              :disabled="isDisabled"
              placeholder=""/>
          </a-form-item>
        </a-col>

        <a-col v-if="!isReadOnly" :xs="24" :sm="12">
          <a-form-item label="客户信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-search-select-tag v-decorator="['customerId', validatorRules.customerId]" :disabled="isDisabled"
                                 :async="true"    dict="zcgl_customer_info,name,id"/>
          </a-form-item>
        </a-col>

        <a-col :xs="24" :sm="12">
          <a-form-item label="款项说明" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-dict-select-tag type="list" v-decorator="['paymentInstructions', validatorRules.paymentInstructions]" :disabled="isDisabled"
                               :trigger-change="true" dictCode="payment_instructions" placeholder="请选择款项说明"></j-dict-select-tag>
          </a-form-item>
        </a-col>

        <a-col :xs="24" :sm="12">
          <a-form-item label="开始日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-date placeholder="请选择开始日期" v-decorator="['startTime', validatorRules.startTime]" :disabled="isDisabled"
                    :trigger-change="true" style="width: 100%"/>
          </a-form-item>
        </a-col>

        <a-col :xs="24" :sm="12">
          <a-form-item label="结束日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-date placeholder="请选择结束日期" v-decorator="['endTime', validatorRules.endTime]" :disabled="isDisabled"
                    :trigger-change="true" style="width: 100%"/>
          </a-form-item>
        </a-col>

        <a-col :xs="24" :sm="12">
          <a-form-item label="应收金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number v-decorator="['amountMoney']" :disabled="isDisabled"  style="width: 100%"/>
          </a-form-item>
        </a-col>

        <a-col :xs="24" :sm="12">
          <a-form-item label="未收金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number v-decorator="['unAmountMoney']" :disabled="isDisabled"  style="width: 100%"/>
          </a-form-item>
        </a-col>

        <a-col :xs="24" :sm="12" v-if='da.type == 1'>
          <a-form-item label="预存金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-decorator="['amountDeposited']" :disabled="isDisabled" />
          </a-form-item>
        </a-col>

<!--        <a-col :xs="24" :sm="12">-->
<!--          <a-form-item label="收款金额" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--            <a-input-number v-decorator="['payeeAmount', validatorRules.payeeAmount]" :disabled="da.type == 2" placeholder="请输入收款金额" style="width: 100%"/>-->
<!--          </a-form-item>-->
<!--        </a-col>-->

<!--        <a-col :xs="24" :sm="12" v-if='da.type == 1'>-->
<!--          <a-form-item label="支付方式" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--            <j-dict-select-tag type="list" v-decorator="['payType', validatorRules.payType]" :trigger-change="true" dictCode="pay_type" placeholder="请选择支付方式"/>-->
<!--          </a-form-item>-->
<!--        </a-col>-->

<!--        <a-col :xs="24" :sm="12" v-if='da.type == 1'>-->
<!--          <a-form-item label="收款日期" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--            <j-date placeholder="请选择收款日期" v-decorator="['receiptDate', validatorRules.receiptDate]" :trigger-change="true"-->
<!--                    style="width: 100%"/>-->
<!--          </a-form-item>-->
<!--        </a-col>-->

<!--        <a-col :xs="24" :sm="12" v-if='da.type == 1'>-->
<!--          <a-form-item label="收款人" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--            <j-search-select-tag v-decorator="['payeeBy']" dict="sys_user,realname,id" placeholder="请选择收款人" />-->
<!--          </a-form-item>-->
<!--        </a-col>-->

<!--        <a-col :xs="24" :sm="12" v-if='da.type == 1'>-->
<!--          <a-form-item label="付款人" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--            <j-search-select-tag v-decorator="['paymentBy', validatorRules.paymentBy]" :trigger-change="true"-->
<!--                                 :dictOptions="paymentByList" />-->
<!--          </a-form-item>-->
<!--        </a-col>-->

<!--        <a-col :xs="24" :sm="12" v-if='da.type == 1'>-->
<!--          <a-form-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--            <j-upload v-decorator="['attachment']"  :trigger-change="true"></j-upload>-->
<!--          </a-form-item>-->
<!--        </a-col>-->

<!--        <a-col :span="24" v-if='da.type == 1'>-->
<!--          <a-form-item label="收款说明" :labelCol="labelCol2" :wrapperCol="wrapperCol2">-->
<!--            <a-textarea v-decorator="['payeeRemark']" rows="4" placeholder="请输入收款说明"/>-->
<!--          </a-form-item>-->
<!--        </a-col>-->

<!--        <a-col :span="24" v-if='da.type == 1'>-->
<!--          <a-form-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2">-->
<!--            <a-textarea v-decorator="['remark']"  :disabled="isDisabled" rows="4" placeholder="请输入备注"/>-->
<!--          </a-form-item>-->
<!--        </a-col>-->

      </a-row>
    </a-form>

    <a-tabs v-model="activeKey"><!--@change="handleChangeTabs"-->
      <a-tab-pane tab="拆费明细" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="false"
          :columns="columns"
          :dataSource="dataSource"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="false"
          :actionButton="false"
          :disabled="disableSubmit"
          @inputBlur="handleInputBlur"
          @valueChange="handleValueChange">

          <!--          <span  slot="action" slot-scope="text, record">-->
          <!--            <a @click="handleDelete(props)">删除</a>-->
          <!--          </span>-->

          <template v-slot:action="props">
              <span v-show="!disableSubmit" v-if="props.index > 0">
                <a @click="handleDelete(props)">删除</a>
                <a-divider type="vertical" />
              </span>
            <a v-show="!disableSubmit" @click="handleAdd(props)">添加</a>
          </template>
        </j-editable-table>

      </a-tab-pane>

    </a-tabs>

    <!--      &lt;!&ndash; 子表单区域 &ndash;&gt;-->
    <!--      <j-editable-table :columns="columns" :dataSource="dataSource" width="100%">-->
    <!--        &lt;!&ndash; 定义插槽 &ndash;&gt;-->
    <!--        &lt;!&ndash; 这种定义插槽的写法是vue推荐的新版写法（https://cn.vuejs.org/v2/guide/components-slots.html#具名插槽），旧版已被废弃的写法不再支持 &ndash;&gt;-->
    <!--        &lt;!&ndash; 若webstorm这样写报错，请看这篇文章：https://blog.csdn.net/lxq_9532/article/details/81870651 &ndash;&gt;-->
    <!--        <template v-slot:action="props">-->
    <!--          <a @click="handleDelete(props)">删除</a>-->
    <!--        </template>-->
    <!--      </j-editable-table>-->

  </a-spin>
</template>

<script>

import '@/assets/less/TableExpand.less'
import pick from 'lodash.pick'
import JDate from '@/components/jeecg/JDate'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import JEditableTable from '@/components/jeecg/JEditableTable'
import { dateAdd, sortTimeKey, divTime } from '@/utils/util'
import {
  VALIDATE_NO_PASSED,
  getRefPromise,
  validateFormAndTables,
  FormTypes,
  validateTables
} from '@/utils/JEditableTableUtil'
import { toll, demolitionFee } from '@/api/receivables'
import { queryById } from '@/api/customer'
import { AssetSubMixin } from '@/api/assetSubMixin'
import JUpload from '@comp/jeecg/JUpload'

export default {
  name: 'ReceivablesOperationModal',
  mixins: [AssetSubMixin],
  components: {
    JEditableTable,
    JUpload,
    JDate,
    JDictSelectTag,
    JSearchSelectTag
  },
  data () {
    return {
      form: this.$form.createForm(this),
      title: '操作',
      paymentByList: [],
      width: 800,
      visible: false,
      isDisabled: true,
      model: {},
      da: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      confirmLoading: false,
      isReadOnly: false,
      validatorRules: {
        payeeAmount: {
          rules: [
            { required: false, message: '请输入收款金额!' }
          ]
        },
        assetSubIds: {
          rules: [
            { required: false, message: '请输入资产明细!' }
            // { validator: this.validateCode }
          ]
        },
        payType: {
          rules: [
            { required: false, message: '请输入支付方式!' }
          ]
        },
        receiptDate: {
          rules: [
            { required: false, message: '请选择收款日期!' }
          ]
        },
        paymentBy: {
          rules: [
            { required: false, message: '请选择付款人!' }
          ]
        }
      },
      // table
      refKeys: ['receivablesDetails'],
      tableKeys: ['receivablesDetails'],
      activeKey: 'receivablesDetails',
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'index',
          width: '10%',
          align: 'center',
          fixed: "left",
          customRender: (text, record, index) =>
            `${(this.ipagination.current - 1) * this.ipagination.pageSize + index + 1}`
        },
        {
          title: '开始日期',
          type: FormTypes.date,
          key: 'startDate',
          width: '25%',
          placeholder: '请输入${title}',
          defaultValue: '',
          validateRules: [{ required: true, message: '${title}不能为空' }],
          customRender: function (text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          },
          align: 'center'
        },
        {
          title: '收款金额',
          type: FormTypes.inputNumber,
          key: 'amountMoney',
          width: '20%',
          placeholder: '请输入${title}',
          defaultValue: '',
          customRender: function (text) {
            return !text ? '0.00' : text.toFixed(2);
          },
          // validateRules: [{ required: true, message: '${title}不能为空' }],
          validateRules: [
            { required: true, message: '${title}不能为空' },
            { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '请输入零以上的数字' },
          ],
          align: 'center'
        },
        {
          title: '备注',
          type: FormTypes.input,
          key: 'remark',
          width: '25%',
          placeholder: '请输入${title}',
          defaultValue: '',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          align: 'center',
          width: '20%',
          type: FormTypes.slot, // 定义该列为 自定义插值列
          slotName: 'action' // slot 的名称，对应 v-slot 冒号后面和等号前面的内容
          // // align:"center",
          // // fixed:"right",
          // // width:147,
          // scopedSlots: { customRender: 'action' }
        }
      ],
      dataSource: [
        {
          startDate: '',
          amountMoney: 0,
          remark: ''
        }
      ],
      url: {
        demolitionFeeCheckModel: '/zcgl/receivablesInfo/demolitionFeeCheckModel'
      },
    }
  },
  created () {
  },
  methods: {
    getAllTable () {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    handleInputBlur(props){
      const { type, row, column, value, target } = props
      var index = row.index
      if (column.key === 'amountMoney') {
        if (value != '' && parseFloat(value) > 0) {
          if (!this.dataSource[index-1].amountMoney && value == this.dataSource[index-1].amountMoney){
            return
          }
          if (this.dataSource.length == 1) {
            this.listAdd(1,"", parseFloat((this.model.unAmountMoney - value).toFixed(2)))
          } else {
          }
          this.dataSource[index-1].amountMoney = value.toFixed(2)
          this.splitDateMoney(index)
          this.sorts()
        } else {
          this.$message.warning('请输入大于0的金额！')
        }
        // this.sorts()
      }
    },
    handleValueChange (props) {
      const { type, row, column, value, target } = props
      var a = value
      var t = 0
      var index = row.index
      if (column.key === 'startDate') {
        t = -1
        if (divTime(value, this.model.endTime) <= 0) {
          this.$message.warning('日期不能在合同结束日期之后')
        } else if (divTime(this.model.startTime, value) <= 0) {
          // a = this.model.startTime
          this.$message.warning('日期不能在合同开始日期之前')
        } else {
          if (!this.listRepeat('startDate', value)) {
            if (index == 1) {
              index = 2
              this.listAdd(1, value, 0)
            } else {
              this.dataSource[index - 1].startDate = value
            }
          } else {
            this.$message.warning('日期已存在')
          }
        }
        this.sorts()
        this.splitAmountMoney()
      } else if (column.key === 'amountMoney') {
      } else {
        this.chageDate(index - 1, column.key, value)
      }
    },
    chageDate (index, key, value) {
      this.dataSource[index][key] = value
    },
    splitAmountMoney () {

      var svgMoney = this.model.unAmountMoney / divTime(this.model.startTime, this.model.endTime)
      var lastDate = this.model.endTime
      for (var i = this.dataSource.length - 1; i >= 0; i--) {
        if (this.dataSource[i].startDate != undefined && this.dataSource[i].startDate != '') {
          var day = divTime(this.dataSource[i].startDate, lastDate)
          this.dataSource[i].amountMoney = parseFloat((svgMoney * day).toFixed(2))
          lastDate = this.dataSource[i].startDate
        }
      }
    },
    //计算检测金额
    splitDateMoney (index) {

      let total =0;
      //循环到当前
      for (let i = 0; i < index; ) {
        if (this.dataSource[i].amountMoney == undefined || this.dataSource.amountMoney == "" || parseFloat(this.dataSource.amountMoney) <= 0){
          this.dataSource.splice(i, 1)
          continue
        }
        total = total + parseFloat(this.dataSource[i].amountMoney)
        i++
      }

      total = parseFloat(total.toFixed(2));
      let money = parseFloat(this.model.unAmountMoney.toFixed(2));
      if (total > money){
        this.$message.warning('拆分后的总金额错误')
        return
      } else if (total == money){
        if (this.dataSource.length > index){
          this.dataSource.splice(index, this.dataSource.length-index)
        }
      } else if (total < money){
        if (this.dataSource.length > index){
          for (let i = index; i < this.dataSource.length; ){
            if (this.dataSource[i].amountMoney == undefined || this.dataSource[i].amountMoney == "" || parseFloat(this.dataSource[i].amountMoney) <= 0.01){
              this.dataSource.splice(i, 1)
              continue
            }
            let newTotal = total + parseFloat(this.dataSource[i].amountMoney)
            if (parseFloat(newTotal.toFixed(2)) < money){
              i++
              total = newTotal
              continue
            }

            this.dataSource[i].amountMoney = (money - total).toFixed(2)
            let a = parseInt(i)+1;
            if (this.dataSource.length > a){
              this.dataSource.splice(a, this.dataSource.length-i)
            }
            total = newTotal
            break
          }
          if (total < money){
            this.listAdd(-1,"", parseFloat((money - total).toFixed(2)))
          }
        } else {
          this.listAdd(-1,"",  parseFloat((money - total).toFixed(2)))
        }
      }
      this.calculationDate()
    },
    //根据金额计算日期
    calculationDate(){
      //保存总共的金额
      let total =0;
      //总共有多少天
      let totalDay = divTime(this.model.startTime, this.model.endTime)
      //平均每天的金额
      let svgMoney = this.model.unAmountMoney / totalDay
      for (let i = 0; i < this.dataSource.length;i++){
        if (i == 0){
          this.dataSource[0].startTime = this.model.startTime
        } else {
          //根据总金额和每天的金额，计算多少天
          let day = total/svgMoney
          this.dataSource[i].startDate = dateAdd ("d", day+1, this.model.startTime)
        }
        total = total + parseFloat(this.dataSource[i].amountMoney)
        this.dataSource[i].index = i+1
      }
    },
    sorts () {
      //根据日期排序
      this.dataSource = sortTimeKey(this.dataSource, 'startDate')
      this.dataSource.forEach(function (item, index) {
        item.index = index + 1
      })
    },
    listAdd (index, startDate, amountMoney) {
      if (index >= 0){
        this.dataSource.splice(index, 0, { index: index, startDate: startDate, amountMoney: parseFloat(amountMoney).toFixed(2)})
      } else {

        this.dataSource.push({ startDate: startDate, amountMoney: parseFloat(amountMoney).toFixed(2)})
      }
    },
    listDel (index) {
      this.dataSource.splice(index, 1)
    },
    listRepeat (key, value) {
      var bool = false
      for (var i = 0; i < this.dataSource.length; i++) {
        if (this.dataSource[i][key] == value) {
          bool = true
          break
        }
      }
      return bool
    },
    /* a 标签的点击事件，删除当前选中的行 */
    handleDelete (props) {
      let { rowId, target, index } = props
      if (this.dataSource.length > 1) {
        this.listDel(index)
      } else {
        this.$message.warning('最后一条数据不能删除')
      }
      this.splitAmountMoney()
      this.sorts()
    },
    handleAdd (props) {
      let { rowId, target, index } = props
      this.listAdd(index + 1, '', 0)
      this.sorts()
    },

    showModal (record) {
      let that = this
      this.confirmLoading = false
      this.form.resetFields()
      this.model = Object.assign({}, record)
      if (this.model.leaseContractId) {
        this.isReadOnly = true
      } else {
        this.isReadOnly = false
      }
      this.selectSub1(this.model.assetId, this.model.assetSubIds)
      this.visible = true
      this.$nextTick(() => {
        let keys = Object.keys(this.form.formItems)
        this.form.setFieldsValue(pick(this.model, keys))
      })
      if (this.model.demolitionFeeList) {
        this.dataSource = this.model.demolitionFeeList
      } else {
        this.dataSource = []
        this.dataSource.push({ index: 1, startDate: record.startTime, amountMoney: record.amountMoney })
      }
    },
    /** 整理成formData */
    classifyIntoFormData (allValues) {
      let that = this
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        demolitionFeeList: allValues.tablesValue[0].values
      }
    },
    cancel (key) {
      let target = this.data.filter(item => item.key === key)[0]
      target.editable = false
    },
    handleChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    close () {
      this.$emit('close')
      this.visible = false
    },
    handleCancel () {
      this.close()
    },
    popupCallback (row) {
      let keys = Object.keys(this.form.formItems)
      this.form.setFieldsValue(pick(row, keys))
    }

  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>